/*
 * Copyright 2009 Kaspar Minosiants http://www.minosiants.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.minosiants.confluence.blog.plugin.impl.tweet2it;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.minosiants.confluence.blog.plugin.tweet2it.IHttpClient;
/**
 *	Project home: http://tweet2it.minosiants.com
 *
 *  @author Kaspar Minosiants
 *
 * 	$Id:$
 */
public class GeneralHttpClient implements IHttpClient {
	private HttpClient httpclient;
	private Log logger = LogFactory.getLog(getClass());
	
	public GeneralHttpClient(){
		
		createHttpClient();
	}
	/* (non-Javadoc)
	 * @see com.minosiants.confluence.blog.plugin.twitter.IHttpClient#get(java.lang.String)
	 */
	public String get(String url) {
		HttpGet httpget = new HttpGet(url);
		try {
			beforeRequest(httpget);
			HttpResponse response=httpclient.execute(httpget);			
			afterRequest(response);
			String responsText=EntityUtils.toString(response.getEntity());
			checkStatus(response.getStatusLine(),responsText);
			return responsText;

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private void checkStatus(StatusLine statusLine,String responsText) {
		if(statusLine==null)
			return;
		int statusCode=statusLine.getStatusCode();
		logger.debug("Http response statusLine: "+statusLine);
		if(statusLine.getStatusCode()!=200)
			logger.error("Http error: "+responsText);
	}
	/* (non-Javadoc)
	 * @see com.minosiants.confluence.blog.plugin.twitter.IHttpClient#post(java.lang.String)
	 */
	public String post(String url){
		return post(url,Collections.EMPTY_MAP);
	}
	private List<NameValuePair> convertMap(Map<String,String> params){
		List<NameValuePair> data= new ArrayList<NameValuePair>();
		Set<Map.Entry<String, String>> set=params.entrySet();
		for (Entry<String, String> entry : set) {
			data.add(new BasicNameValuePair( entry.getKey(), entry.getValue()));	
		}		
		return data;
	}
	public String post(String url,Map<String,String> params){	
		logger.debug("url: "+url);		
		try {
			HttpPost pm= new HttpPost(url);
			pm.addHeader("Content-Type", "application/x-www-form-urlencoded");										
			pm.setEntity(new UrlEncodedFormEntity(convertMap(params), HTTP.UTF_8));
			beforeRequest(pm);
			HttpProtocolParams.setUseExpectContinue(httpclient.getParams(), false);
			HttpProtocolParams.setUseExpectContinue(pm.getParams(), false);
			HttpResponse response = httpclient.execute(pm);
			afterRequest(response);
			String responsText=EntityUtils.toString(response.getEntity());
			checkStatus(response.getStatusLine(),responsText);
			return responsText;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		return null;
	}
	protected void beforeRequest(HttpRequest request){}
	protected void afterRequest(HttpResponse response){}
	
	private void createHttpClient() {
		HttpClient client = new DefaultHttpClient();
		ClientConnectionManager mgr = client.getConnectionManager();
		if (!(mgr instanceof ThreadSafeClientConnManager)) {
			HttpParams params = client.getParams();
			client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
		}
		this.httpclient = client;
	}
		
	
}
